import uuid
import random
from sale.apps.member.dal import get_user_info_by_name
from sale.apps.member.dal import select_package
from sale.apps.member.dal import select_package_by_id
from sale.apps.member.dal import get_user_info_by_phone
from sale.apps.member.dal import query_unused_verify_code
from sale.apps.member.dal import add_user_info
from sale.apps.member.dal import add_verify_code
from sale.apps.member.dal import update_verify_code
from sale.apps.member.dal import add_create_order
from sale.apps.member.dal import select_my_orders
from sale.apps.member.dal import select_order_info


from sale.utils.veriy_code import create_code
from sale.apps.member.dal import query_verify_code_by_pt, count_verify_code_by_pt
import datetime
from flask import session


def login_bll(name, password):
    user = get_user_info_by_name(name)
    if not user:
        return {'msg': "用户不存在", 'code': 'fail'}
    if password != user.password:
        return {'msg': "密码错误", 'code': 'fail'}
    token = str(uuid.uuid4())
    session[token] = {'username': user.name, 'user_phone': user.phone, 'userid': user.id}
    return {'name': user.name, 'code': 'success', 'token': token}


def register_bll(name, phone, verify_code, md5_data_one):
    user = get_user_info_by_name(name)
    if user:
        return {'msg': "用户已存在，请重新输入", 'code': "fail"}
    user = get_user_info_by_phone(phone)
    if user:
        return {'msg': "手机号已存在，请重新输入", 'code': "fail"}
    record = query_unused_verify_code(phone=phone, verify_code=verify_code)
    if not record:
        return {'msg': "验证码不正确", 'code': "fail"}
    add_success = add_user_info(name, phone, md5_data_one)
    if not add_success:
        return {'msg': "注册失败", 'code': "fail"}
    update_verify_code(phone, verify_code)
    return {'msg': "注册成功", 'code': "success"}


def select_bll(name):
    user = get_user_info_by_name(name)
    if not user:
        return {'msg': "用户不存在，请重新输入"}
    return {'msg': "查询成功\n", 'name': user.name, 'phone': user.phone}


def is_exist_bll(name=None, phone=None):
    if name is None and phone is None:
        return False, '不能同时为空'
    if name:
        user = get_user_info_by_name(name)
        if not user:
            return False, '用户不存在'
    if phone:
        user_phone = get_user_info_by_phone(phone)
        if not user_phone:
            return False, '手机不存在'
    return True, None


def send_verify_code_bll(phone):
    if not session.get('image_verify_code_success'):
        return False, "图片验证失败"
    time_ = datetime.datetime.now() - datetime.timedelta(minutes=1)
    record = query_verify_code_by_pt(phone=phone, time_=time_)
    if record:
        return False, "发送太频繁"
    count = count_verify_code_by_pt(phone, datetime.datetime.now() - datetime.timedelta(minutes=5))
    if count >= 3:
        return False, "发送太多，请5分钟后再试"
    code = create_code()
    record = add_verify_code(phone, code, datetime.datetime.now())
    return record, None


def image_verify_code_bll(image_verify_code):
    print(session.get('image_verify_code'))
    if image_verify_code == session.get('image_verify_code'):
        session['image_verify_code_success'] = True
        return {'msg': "图片验证成功", 'code': "success"}
    else:
        session['image_verify_code_success'] = False
        return {'msg': "图片验证失败", 'code': "fail"}


def get_phone_bll(username):
    user_info = get_user_info_by_name(username)
    if not user_info:
        return {'msg': "获取失败", 'code': "fail"}
    user_name = user_info.name
    phone = user_info.phone
    return {'msg': "请求成功",
            'code': "success",
            "user_info": {'name_': user_name, 'phone': phone}
            }


def select_package_bll():
    packages = select_package()
    package_info = []
    for package in packages:
        tmp = {
            "id": package.id,
            "original_price": float(package.original_price),
            "pay_price": float(package.discount_price)
        }
        package_info.append(tmp)
    return True, package_info


def create_order_bll(
        phone, package_id, user_id, user_phone
):
    # 获取套餐信息
    package = select_package_by_id(package_id)
    if not package:
        return False, "套餐不存在"
    # 生成订单
    order_no = "%s%s" % (datetime.datetime.now().strftime("%Y%m%d%H%M%S"), random.randint(10000, 99999))
    goods_desc = '%s：充值面额%s元' % (phone, package.original_price)
    order_info = add_create_order(
        user_id=user_id, user_phone=user_phone,
        package_id=package_id, face_value=package.original_price,
        deposit_phone=phone, pay_amount=package.discount_price,
        order_no=order_no, goods_desc=goods_desc
    )
    # 第三方生成订单
    from wechatpy import WeChatPay
    from flask import request
    # if 'HTTP_X_FORWARDED_FOR' in request.META:
    #     ipaddress = request.META['HTTP_X_FORWARDED_FOR']
    # else:
    #     ipaddress = request.META['REMOTE_ADDR']
    ipaddress = '117.176.186.72'
    wx_pay = WeChatPay(
        
    )
    pay_info = wx_pay.order.create(
        trade_type='MWEB', body=goods_desc, total_fee=2,
        notify_url='http://127.0.0.1/api/sale/v1/order/notify', spbill_create_ip=ipaddress,
        out_trade_no=order_no)
    # wx_pay.tools.ver
    return True, {'order_info': {'order_no': order_no}, 'pay_info': pay_info}


def my_orders_bll(user_phone):
    user_orders = select_my_orders(user_phone=user_phone)
    if not user_orders:
        return False, "暂无订单信息"
    order_info = []
    for user_order in user_orders:
        if user_order.order_status == "INIT":
            user_order.order_status = "订单未支付"
        if user_order.order_status == "PAY_FINISH":
            user_order.order_status = "支付成功"
        if user_order.order_status == "REFUNDING":
            user_order.order_status = "正在退款中"
        if user_order.order_status == "REFUND_FINISH":
            user_order.order_status = "退款成功"
        tmp = {
            "充值手机号": user_order.pay_no,
            "支付金额": float(user_order.pay_amount),
            "创建订单时间": user_order.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            "订单状态": user_order.order_status,
            "订单号": user_order.order_no
        }
        order_info.append(tmp)
    return True, order_info


def order_detail_bll(order_no):
    order_info = select_order_info(order_no=order_no)
    if order_info.order_status == "INIT":
        order_info.order_status = "订单未支付"
    if order_info.order_status == "PAY_FINISH":
        order_info.order_status = "支付成功"
    if order_info.order_status == "REFUNDING":
        order_info.order_status = "正在退款中"
    if order_info.order_status == "REFUND_FINISH":
        order_info.order_status = "退款成功"
    tmp = {
        "订单号": order_info.order_no,
        "充值手机号": order_info.pay_no,
        "套餐原价": float(order_info.face_value),
        "支付金额": float(order_info.pay_amount),
        "订单描述": order_info.goods_desc,
        "支付时间": order_info.pay_time.strftime('%Y-%m-%d %H:%M:%S'),
        "支付状态": order_info.order_status,
        "创建订单时间": order_info.create_time.strftime('%Y-%m-%d %H:%M:%S'),
        "更新订单时间": order_info.update_time.strftime('%Y-%m-%d %H:%M:%S')
    }
    return tmp
